package com.talkyun.openx.server;

import com.talkyun.openx.server.core.ServiceRequest;
import com.talkyun.utils.codec.Base62;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class AbstractHandler {

    protected String read(InputStream ins, String charset) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 4);
        byte[] buf = new byte[1024];
        int num = ins.read(buf);
        while (num != -1) {
            baos.write(buf, 0, num);
            num = ins.read(buf);
        }
        return baos.toString(charset);
    }

    protected void readToMessage(HttpServletRequest req, ServiceRequest msg) {

    }

    protected String[] splitIgnoreBlank(String src, String split) {
        if (isBlank(src)) {
            return new String[0];
        }

        String[] parts = src.split("/");
        List<String> result = new ArrayList<String>(parts.length);
        for (String p : parts) {
            if (isBlank(p)) {
                continue;
            }
            result.add(p.trim());
        }
        return result.toArray(new String[result.size()]);
    }

    protected String getLastURI(String uri, String ctx) {
        String[] tmp = splitIgnoreBlank(ctx, "/");
        String fineCtx = tmp.length == 0 ? "" : tmp[0];

        String[] parts = splitIgnoreBlank(uri, "/");
        if (parts.length == 0 || (parts.length == 1 && parts[0].equals(fineCtx))) {
            return "/";
        }

        StringBuilder sb = new StringBuilder();
        for (int x = (parts[0].equals(fineCtx) ? 1 : 0); x < parts.length; x++) {
            sb.append("/").append(parts[x]);
        }

        return sb.toString();
    }

    protected String encodeToB62(String txt){
        return Base62.encode(txt);
    }

    protected String decodeFromB62(String txt){
        return Base62.decode(txt);
    }

    protected boolean isBlank(String args) {
        return args == null || args.trim().length() == 0;
    }

}